package dataGoods

import (
	"context"
	"github.com/golang/protobuf/ptypes/empty"
	goods_pb "mxshop/api/goods/v1"
	IGoods "mxshop/app/mxshop_api/api/internal/data/goods"
	doGoods "mxshop/app/mxshop_api/api/internal/domain/do/goods"
	"mxshop/gmicro/pkg/errors"
)

type banner struct {
	gc goods_pb.GoodsClient
}

func (b *banner) List(ctx context.Context) (*doGoods.BannerDOList, error) {
	var ret doGoods.BannerDOList

	rsp, err := b.gc.BannerList(ctx, &empty.Empty{})
	if err != nil {
		return nil, errors.FromGrpcError(err)
	}

	for _, v := range rsp.Data {
		ret.Items = append(ret.Items, &doGoods.BannerDO{
			Id:    v.Id,
			Index: v.Index,
			Image: v.Image,
			Url:   v.Url,
		})
	}
	ret.TotalCount = int64(rsp.Total)

	return &ret, nil
}

func (b *banner) Create(ctx context.Context, request *doGoods.BannerDO) error {
	protoBanner := &goods_pb.BannerRequest{
		Id:    request.Id,
		Index: request.Index,
		Image: request.Image,
		Url:   request.Url,
	}
	rsp, err := b.gc.CreateBanner(ctx, protoBanner)
	if err != nil {
		return errors.FromGrpcError(err)
	}
	request.Id = rsp.Id
	return nil
}

func (b *banner) Update(ctx context.Context, request *doGoods.BannerDO) error {
	protoBanner := &goods_pb.BannerRequest{
		Id:    request.Id,
		Index: request.Index,
		Image: request.Image,
		Url:   request.Url,
	}
	_, err := b.gc.UpdateBanner(ctx, protoBanner)
	if err != nil {
		return errors.FromGrpcError(err)
	}
	return nil
}

func (b *banner) Delete(ctx context.Context, id int64) error {
	_, err := b.gc.DeleteBanner(ctx, &goods_pb.BannerRequest{Id: id})
	if err != nil {
		return errors.FromGrpcError(err)
	}
	return nil
}

func newBanner(gc goods_pb.GoodsClient) IGoods.Banner {
	return &banner{
		gc: gc,
	}
}
